import type { FC } from 'react';
import { useRef } from 'react';
import { ColorPicker, Divider, Space, Button } from 'antd';
import { useMemoizedFn, useSafeState } from 'ahooks';
import { recommendColors } from './color.json';
import styles from './styles.module.less';

type ColorPickerProProps = {
  value?: string;
  onChange?: (value: string) => void;
}

const prcikerStyles = {
  popupOverlayInner: {
    width: 492
  }
}

const presets = [
  {
    label: '常用颜色',
    colors: recommendColors,
  }
];

const ColorPickerPro: FC<ColorPickerProProps> = (props) => {
  const color = useRef(props.value);
  const [open, setOpen] = useSafeState(false);

  const handleChange = useMemoizedFn((_, val: string) => {
    color.current = val;
  });

  const handleClose = useMemoizedFn(() => {
    setOpen(false);
  });

  const handleOk = useMemoizedFn(() => {
    const _color = color.current;
    handleClose();
    if (_color) props.onChange?.(_color);
  });

  return (
    <ColorPicker
      open={open}
      presets={presets}
      value={props.value}
      styles={prcikerStyles}
      onOpenChange={setOpen}
      onChange={handleChange}
      className={styles.picker_container}
      panelRender={(_, e) => {
        const { Picker, Presets } = e.components;
        return (
          <div className={styles.container}>
            <div className={styles.presets}>
              <Presets />
            </div>
            <Divider
              type="vertical"
              className={styles.line}
            />
            <div className={styles.picker}>
              <Picker />
              <div className={styles.buttons}>
                <Space>
                  <Button
                    size="small"
                    children="取消"
                    onClick={handleClose}
                  />
                  <Button
                    size="small"
                    type="primary"
                    children="确定"
                    onClick={handleOk}
                  />
                </Space>
              </div>
            </div>
          </div>
        );
      }}
    />
  );
};

export default ColorPickerPro;
